package com.smartHome.service.impl;

import com.smartHome.mapper.HouseMapper;
import com.smartHome.pojo.entity.House;
import com.smartHome.pojo.vo.HouseDetailVO;
import com.smartHome.pojo.vo.HouseListVO;
import com.smartHome.pojo.vo.HouseVO;
import com.smartHome.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HouseServiceImpl implements HouseService {

    @Autowired
    private HouseMapper houseMapper;

    @Override
    public List<HouseListVO> getAllHousesWithMembers(Integer userId) {
        // 1. 获取所有房子的基本信息
        List<HouseListVO> houses = houseMapper.getAllHouses(userId);

        // 2. 为每个房子获取成员信息
        for (HouseListVO house : houses) {
            house.setMembers(houseMapper.getHouseMembers(house.getHouseId()));
        }

        return houses;
    }

    @Override
    public List<HouseVO> getByUserId(Integer userId) {
        // 获取用户的房子列表
        List<HouseVO> houses = houseMapper.getByUserId(userId);
        return houses;
    }

    @Override
    public Integer getHouseOnlineDevices(Integer houseId) {
        return houseMapper.countHouseOnlineDevices(houseId);
    }

    @Override
    @Transactional
    public void addHouse(Integer userId, String houseName) {
        // 创建房子对象
        House house = new House();
        house.setUserId(userId);
        house.setHouseName(houseName);

        // 添加房子，MyBatis会自动设置生成的ID到house对象中
        houseMapper.addHouse(house);

        // 添加创建者作为房子成员
        houseMapper.addHouseMember(house.getHouseId(), userId);
    }

    @Override
    @Transactional
    public void deleteHouses(List<Integer> houseIds) {
        if (houseIds == null || houseIds.isEmpty()) {
            return;
        }
        // 删除顺序：先删除房间 -> 再删除房子成员 -> 最后删除房子
        // 1. 删除房子关联的房间
        houseMapper.deleteHouseRooms(houseIds);
        // 2. 删除房子成员关系
        houseMapper.deleteHouseMembers(houseIds);
        // 3. 删除房子
        houseMapper.deleteHouses(houseIds);
    }

    @Override
    public HouseDetailVO getHouseDetail(Integer houseId) {
        HouseDetailVO houseDetail = new HouseDetailVO();

        // 设置房子名称
        houseDetail.setHouseName(houseMapper.getHouseName(houseId));

        // 设置在线设备数
        houseDetail.setOnlineDevicesCount(houseMapper.countHouseOnlineDevices(houseId));

        // 设置房间列表
        houseDetail.setRooms(houseMapper.getHouseRooms(houseId));

        // 设置成员列表
        houseDetail.setMembers(houseMapper.getHouseMembers(houseId));

        return houseDetail;
    }
}
